package service

import (
	"singo/model"
	"singo/serializer"
	"time"

	"github.com/rs/xid"
)

// ProjectCreateService 管理新增项目的服务
type ProjectCreateService struct {
	Name            string `form:"name" json:"name" binding:"required,max=30"`
	Head            string `form:"head" json:"head" binding:"required"`
	Intro           string `form:"intro" json:"intro"`
	OrganizationUID string `form:"organization_id" json:"organization_id"`
	DeadlineAt      string `form:"deadline_at" json:"deadline_at"`
}

// ProjectCreate 新增项目
func (service *ProjectCreateService) ProjectCreate(userUID string) *serializer.Response {
	uid := xid.New()

	project := model.Project{
		UID:             uid.String(),
		Name:            service.Name,
		OrganizationUID: service.OrganizationUID,
		Intro:           service.Intro,
		CreatedBy:       userUID,
		Head:            service.Head,
	}

	if service.DeadlineAt != "" {
		deadlineAt, _ := time.ParseInLocation("2006-01-02 15:04:05", service.DeadlineAt, time.Local)
		project.DeadlineAt = &deadlineAt
	}

	count := 0
	model.DB.Model(&model.Project{}).Where("name = ?", service.Name).Count(&count)
	if count > 0 {
		return &serializer.Response{
			Status: 40001,
			Msg:    "项目名称被占用",
		}
	}

	// 创建项目
	if err := model.DB.Create(&project).Error; err != nil {
		return &serializer.Response{
			Status: 50001,
			Msg:    "项目保存失败",
			Error:  err.Error(),
		}
	}
	return &serializer.Response{
		Data:   true,
		Msg:    "成功",
		Status: 0,
	}
}
